<template>
  <page-container>
    <div class="ant-pro-table-search" @keydown.enter="handleSearch">
      <a-form layout="horizontal"
        :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-row :gutter="20" type="flex" justify="start">
<#if view.codeProperty??>
          <a-col :xs="24" :sm="24" :md="12" :lg="8">
            <a-form-item label="编码">
              <a-input v-model:value="queryParam.code" placeholder="编码" />
            </a-form-item>
          </a-col>
</#if>
<#if view.nameProperty??>
          <a-col :xs="24" :sm="24" :md="12" :lg="8">
            <a-form-item label="名称">
              <a-input v-model:value="queryParam.name" placeholder="名称" />
            </a-form-item>
          </a-col>
</#if>
<#if view.validProperty??>
          <a-col :xs="24" :sm="24" :md="12" :lg="8">
            <a-form-item label="是否有效">
              <a-select v-model:value="queryParam.valid" placeholder="请选择">
                <a-select-option key="">-- 不限 -- </a-select-option>
                <a-select-option key="true">是</a-select-option>
                <a-select-option key="false">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
</#if>
          <a-col :xs="24" :sm="24" :md="12" :lg="8">
            <a-form-item>
              <a-button @click="handleSearch" type="primary">查询</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    
    <div class="ant-pro-table">
      <a-card :body-style="{ padding: 0 }" ref="elRef">
        <!-- toolbar -->
        <com-table-toolbar
          :table-title="'${view.entityComment}列表'"
          @refresh="reload"
          v-model:stripeChecked="fetchDataContext.stripe"
          @select-table-density=" (key) => { fetchDataContext.tableSize = String(key); } "
          :dynamic-columns-context="dynamicColumnsContext"
          :fullscreen-context="fullscreenContext">
          <a-button type="primary" @click="handleOpenAdd">
            <plus-outlined />新建
          </a-button>
        </com-table-toolbar>

        <!-- table -->
        <a-table
          ref="tableRef"
          :getPopupContainer="_trigger => tableRef.$el"
          :row-class-name="stripe"
          :size="state.tableSize"
          :loading="state.loading"
          :columns="dynamicColumns"
          :data-source="state.dataSource"
          :pagination="false"
          :row-key="'id'"
          :rowSelection="{
            hideSelectAll: true,
            type: 'radio',
            selectedRowKeys: [selectedIdRef],
            onSelect: (record) => { selectedIdRef = record.id; },
          }"
          :customRow="(record) => {
            return {
              onClick: () => { selectedIdRef = record.id; },
              onDblclick: () => { handleOpenUpdate(record) },
            };
          }"
          @change="handleTableChange">
          <template #bodyCell="{ column, record }">
<#if view.validProperty??>
            <template v-if="column.dataIndex === 'valid'">
              <template v-if="record.valid == true">
                <a-badge color="green" text="是" />
              </template>
              <template v-else>
                <a-badge color="red" text="否" />
              </template>
            </template>
</#if>
            <template v-if="column.dataIndex === 'action'">
              <a @click="handleOpenUpdate(record)">编辑</a>
              <a-divider type="vertical" />
<#if view.validProperty??>
              <template v-if="record.valid == true">
                <a @click="onDisable(record)">禁用</a>
                <a-divider type="vertical" />
              </template>
              <template v-else>
                <a @click="onEnable(record)">启用</a>
                <a-divider type="vertical" />
              </template>
</#if>
              <a @click="onDelete(record)">删除</a>
              <a-divider type="vertical" />
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </page-container>
  
  <add-component
    :get-container="() => elRef && elRef.$el"
    :visible="addModal.visible"
    @cancel="() => {
      addModal.visible = false;
    }"
    @ok="() => {
      addModal.visible = false;
      reload();
    }"
    :params="addModal.params">
  </add-component>

  <update-component
    :get-container="() => elRef && elRef.$el"
    :visible="updateModal.visible"
    @cancel="() => {
      updateModal.visible = false;
    }"
    @ok="() => {
      updateModal.visible = false;
      reload();
    }"
    :params="updateModal.params">
</update-component>
</template>

<script lang="ts">
    import {computed, defineComponent, reactive, ref} from 'vue';
    import {PlusOutlined} from '@ant-design/icons-vue';
    import {useTableDynamicColumns} from '@/utils/hooks/useTableColumn';
    import {useFullscreen} from '@/utils/hooks/useFullscreen';
    import {queryListWrap, useFetchData} from '@/utils/hooks/useFetchData';

    import {default as ComTableToolbar} from '@/components/table-components/com-table-toolbar.vue';
    import {default as AddComponent} from './add-';
    import {default as UpdateComponent} from './update-';
    import {handleWithConfirmWrap} from '@/utils/commons';
    import {dateFormat} from '@/utils/date-util';
    import {
        deleteById, disableById,

        <#if view.validProperty ?? > enableById, </#if>
        queryList
    }
        from
            '@/api/';
    import {queryList as queryEnumList} from '@/api/basicdata/basic_data_enum';
    import type { DynamicColumnsContext } from '@/utils/hooks/useTableColumn';
    import type { FullscreenContext } from '@/utils/hooks/useFullscreen';
    import type { AddParams } from './add-${view.entityTypeSimpleName?replace("([a-z])([A-Z]+)","$1-$2","r")?lower_case}.vue';
    import type { UpdateParams } from './update-${view.entityTypeSimpleName?replace("([a-z])([A-Z]+)","$1-$2","r")?lower_case}.vue';
    import type { Pagination, TableColumn } from '@/typing';
    import type { ${view.entityTypeSimpleName} } from '@/api/${packageName}/${view.entityTypeSimpleName?replace("([a-z])([A-Z]+)","$1_$2","r")?lower_case}';

    <#if view.isHasBasicDataEnumProperty()>
    </#if>

const formLayout = {
  labelCol: {
    xs: { span: 6 },
    sm: { span: 6 },
    md: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 18 },
    sm: { span: 18 },
    md: { span: 18 },
  },
};
export default defineComponent({
  name: 'Query${view.entityTypeSimpleName}List',
  setup() {
<#list view.propertyList as property>
    <#if property.isBasicdataEnum()>
    const ${property.propertyName}Map = {};
    queryEnumList('${property.propertyTypeSimpleName}').then((res) => {
      res.forEach((d) => {
        ${property.propertyName}Map[d.key] = d;
      });
    });
    </#if>
</#list>
<#if (view.parentIdProperty?? || view.parentProperty??)>
    const ${view.entityTypeSimpleName?uncap_first}Map = {};
    queryList({}).then((res) => {
      res.forEach((d) => {
        ${view.entityTypeSimpleName?uncap_first}Map[d.id] = d;
      });
	});
</#if>

    //customized
    const querier = queryListWrap<${view.entityTypeSimpleName}>(queryList);
    const baseColumns = computed<TableColumn[]>(() => {
      return [
<#list view.viewablePropertyList as property>
	<#if property.isPrimaryKey()>
	<#elseif property.propertyName == "vcid"
		|| property.propertyName == "id"
		|| property.propertyName == "createOperatorId" 
		|| property.propertyName == "lastUpdateOperatorId">
	<#elseif property.propertyName == "parentId">
        {
          title: '${property.propertyComment}',
          dataIndex: '${property.propertyName}',
          customRender: ({ record }) => record.parentId && ${view.entityTypeSimpleName?uncap_first}Map[record.parentId] ? ${view.entityTypeSimpleName?uncap_first}Map[record.parentId].name : '',
        },
	<#elseif property.propertyName == "lastUpdateDate">
        {
          title: '最后更新时间',
          dataIndex: 'lastUpdateDate',
          customRender: ({ record }) => dateFormat(record.lastUpdateDate),
        },
    <#elseif property.propertyName == "createDate">
        {
          title: '创建时间',
          dataIndex: 'createDate',
          customRender: ({ record }) => dateFormat(record.createDate),
        },
	<#else>
    	<#if property.isSimpleValueType()>
        {
          title: '${property.propertyComment}',
          dataIndex: '${property.propertyName}',
            <#if property.isBasicdataEnum()>
          customRender: ({ record }) => record.${property.propertyName} && ${property.propertyName}Map[record.${property.propertyName}] ? ${property.propertyName}Map[record.${property.propertyName}].name : '',
            <#elseif property.propertyTypeSimpleName == 'boolean' || property.propertyTypeSimpleName == 'Boolean'>
          customRender: ({ record }) => record.${property.propertyName} ? '是' : '否',
            <#elseif  property.propertyTypeSimpleName == 'Date'>
          customRender: ({ record }) => dateFormat(record.${property.propertyName}),
            </#if>
		},
		<#elseif property.isBasicdataType()>
		{
          title: '${property.propertyComment}',
          dataIndex: '${property.propertyName}',
          customRender: ({ record }) => record.${property.propertyName} ? record.${property.propertyName}.name : '',
		},
        </#if>
	</#if>
</#list>
        {
          title: '操作',
          dataIndex: 'action',
        },
      ];
    });
            
    //search
    const tableRef = ref();
    //表格选中
    const selectedIdRef = ref<string>();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const onLoadSuccess = (_data: {rows:[],total:number}) => {
      selectedIdRef.value = '';
    };
    const queryParam = reactive({
<#if view.codeProperty??>
      code: '',
</#if>
<#if view.nameProperty??>
      name: '',
</#if>
<#if view.validProperty??>
      valid: '',
</#if>
    });
    //useFetchData
    const fetchDataContext = reactive({
      stripe: true,
      tableSize: 'middle',
      current: 1,
      pageSize: 10,
      requestParams: { ...queryParam },
    });
    const { stripe, context: state, reload } = useFetchData(querier, fetchDataContext, {
      onLoadSuccess: onLoadSuccess,
    });
    const handleTableChange = ({ current, pageSize }: Pagination) => {
      fetchDataContext.current = current;
      fetchDataContext.pageSize = pageSize;
    };
    
    //toolbar:dynamicColumns
    const needRowIndex = ref(false);
    const dynamicColumnsContext = useTableDynamicColumns(baseColumns, { needRowIndex }) as DynamicColumnsContext;
    const { dynamicColumns } = dynamicColumnsContext;
    //toolbar:fullscreen
    const [elRef, screenState, { setFull, exitFull }] = useFullscreen(); //fullscreen
    const fullscreenContext: FullscreenContext = {
      fullscreenState: screenState,
      setFull: setFull,
      exitFull: exitFull,
    };

    //查询
    const handleSearch = () => {
      fetchDataContext.requestParams = { ...queryParam };
    };
    const modelName = '${view.entityComment}';
    //删除
    const deleteHandler = handleWithConfirmWrap(deleteById, modelName, '删除', () => elRef.value && elRef.value.$el);
    const onDelete = (record: ${view.entityTypeSimpleName}) => {
      deleteHandler(record.id, record.name).then((res) => {
        if(res){
          reload();
        }
      });
    };
<#if view.validProperty??>
    //禁用
    const disableHandler = handleWithConfirmWrap(disableById, modelName, '禁用', () => elRef.value && elRef.value.$el);
    const onDisable = (record: ${view.entityTypeSimpleName}) => {
      disableHandler(record.id, record.name).then((res) => {
        if(res){
          reload();
        }
      });
    };
    //启用
    const enableHandler = handleWithConfirmWrap(enableById, modelName, '启用', () => elRef.value && elRef.value.$el);
    const onEnable = (record: ${view.entityTypeSimpleName}) => {
      enableHandler(record.id, record.name).then((res) => {
        if(res){
          reload();
        }
      });
    };
</#if>

    //add-modal
    const addModal = reactive({
      visible: false,
      params: {} as AddParams,
    });
    const handleOpenAdd = () => {
      addModal.params.parentId = String(selectedIdRef.value);
      addModal.visible = true;
    };
            
    //update-modal  
    const updateModal = reactive({
        visible: false,
        params: {} as UpdateParams,
    });
    const handleOpenUpdate = (selecedRecord: ${view.entityTypeSimpleName}) => {
        updateModal.params.id = selecedRecord.id;
        updateModal.visible = true;
    };
    return {
      ...formLayout,
      
      //toolsbar
      tableRef,
      elRef,
      fullscreenContext,
      dynamicColumnsContext,
      dynamicColumns,
      stripe,
      state,
      reload,
      handleTableChange,
      
      //table
      selectedIdRef,
      queryParam,
      fetchDataContext,
      handleSearch,
      
      //action
      onDelete,
<#if view.validProperty??>
      onDisable,
      onEnable,
</#if>
      addModal,
      handleOpenAdd,
      updateModal,
      handleOpenUpdate,
	};
  },
  components: {
    PlusOutlined,
    ComTableToolbar,
    AddComponent,
    UpdateComponent,
  },
});
</script>